/*
 * @Description:
 * @Author: Rfan
 * @Date: 2022-04-28 13:48:21
 * @LastEditTime: 2023-01-05 20:53:17
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Progress, Space, Table, Tag, Typography } from 'antd';
import classNames from 'classnames/bind';
import { CheckCircleFilled } from '@ant-design/icons';
import { formatDate, isNullObj } from '@/utils';
import { useFormatMessage } from '@/utils/intlHelpers';
import { wsState } from '@/store/WSStore';
import { uploadBatch } from '@/api/accession';
import { useBatchManageContext } from '../contexts/BatchManageContext';
import {
  RECEIVE_TYPE_CD,
  RECEIVE_TYPE_DBF,
  RECEIVE_TYPE_EXCEL,
  RECEIVE_TYPE_SIP
} from '../constants';
import UploadFolderDialog from './dialogs/UploadFloder';
import UploadOriginDialog from './dialogs/UploadOrigin';
import UploadSipDialog from './dialogs/UploadSip';
import { observer } from 'mobx-react-lite';
import { ColumnsType } from 'antd/es/table';
import UploadCDDialog from '@/view/accession/BatchManage/components/dialogs/UploadCD';
import { useReceiveTypeContext } from '@/view/accession/BatchManage/contexts/ReceiveWaysContext';
import styles from '../styles/pageList.module.scss';
import UploadDBFDialog from '@/view/accession/BatchManage/components/dialogs/UploadDBF';
import { EnumReceiveWays } from '@/view/accession/BatchManage/dictionaries';
import CreateBatchDialog from '@/view/accession/CollectionAccession/components/dialogs/CreateBatch';

const cx = classNames.bind(styles);

const PageList = (props: any) => {
  const { className } = props;
  const {
    batchList,
    selectItems,
    activeBatch,
    selectReceiveType,
    setActiveBatch,
    setBatchItemProcess,
    getBatchList,
    updateBatchList,
    setSelectKey,
    deleteBatchFunc,
    receiveModeFilter,
    receiveTypeFilter,
    stateFilter
  } = useBatchManageContext();
  const formatMessage = useFormatMessage();

  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [listQuery, setListQuery] = useState<any>({
    pageNo: 1,
    pageSize: 5,
    param: {}
  });
  // 选中的条目
  const [selectData, setSelectData] = useState(null);
  // 归集弹窗显示标志
  const [createVisible, setCreateVisible] = useState(false);
  // 上传文件弹窗显示标志
  const [uploadFolderVisible, setUploadFolderVisible] = useState(false);
  // 上传原文弹窗显示标志
  const [uploadOriginVisible, setUploadOriginVisible] = useState(false);
  // 上传SIP包弹窗显示标志
  const [uploadSipVisible, setUploadSipVisible] = useState(false);
  // 上传CD弹窗显示标志
  const [uploadCDVisible, setUploadCDVisible] = useState(false);
  // 上传DBF弹窗显示标志
  const [uploadDBFVisible, setUploadDBFVisible] = useState(false);

  useEffect(() => {
    setListQuery({
      pageNo: 1,
      pageSize: 10,
      param: {
        businessType: 7
      }
    });
  }, [selectReceiveType]);

  useEffect(() => {
    if (listQuery && !isNullObj(listQuery.param)) {
      setLoading(true);
      getBatchList(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
          setTimeout(() => {}, 2000);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  // 监听ws消息更改进度
  useEffect(() => {
    const { archiveImport } = wsState;
    console.log('ws', archiveImport);
    if (archiveImport) {
      setBatchItemProcess(archiveImport);
    }
  }, [wsState.archiveImport]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state: any) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  /**
   * @description: 打开上传目录弹窗
   * @param {any} item
   * @return {void}
   */
  const showUploadFolderDialog = (item: any): void => {
    setActiveBatch(item);
    setUploadFolderVisible(true);
  };

  /**
   * @description: 关闭上传目录弹窗
   * @param {any} record
   * @return {void}
   */
  const closeUploadFolderDialog = (record: any): void => {
    setUploadFolderVisible(false);
    setActiveBatch({});
    if (record) {
      updateBatchList(record);
    }
  };

  /**
   * @description: 打开上传目录弹窗
   * @param {any} item
   * @return {void}
   */
  const showUploadOriginDialog = (item: any): void => {
    setActiveBatch(item);
    setUploadOriginVisible(true);
  };

  /**
   * @description: 关闭上传目录弹窗
   * @param {any} record
   * @return {void}
   */
  const closeUploadOriginDialog = (record: any): void => {
    setUploadOriginVisible(false);
    setActiveBatch({});
    if (record) {
      updateBatchList(record);
    }
  };

  /**
   * @description: 打开上传SIP包目录弹窗
   * @param {any} item
   * @return {void}
   */
  const showUploadSipDialog = (item: any): void => {
    setActiveBatch(item);
    setUploadSipVisible(true);
  };

  /**
   * @description: 关闭上传目录弹窗
   * @param {any} record
   * @return {void}
   */
  const closeUploadSipDialog = (record: any): void => {
    setUploadSipVisible(false);
    setActiveBatch({});
    if (record) {
      updateBatchList(record);
    }
  };

  /**
   * @description: 打开上传CD弹窗
   * @param {any} item
   * @return {void}
   */
  const showUploadCDDialog = (item: any): void => {
    setActiveBatch(item);
    setUploadCDVisible(true);
  };

  /**
   * @description: 关闭上传CD弹窗
   * @param {any} record
   * @return {void}
   */
  const closeUploadCDDialog = (record: any): void => {
    setUploadCDVisible(false);
    setActiveBatch({});
    if (record) {
      updateBatchList(record);
    }
  };

  /**
   * @description: 打开上传SIP包目录弹窗
   * @param {any} item
   * @return {void}
   */
  const showUploadDBFDialog = (item: any): void => {
    setActiveBatch(item);
    setUploadDBFVisible(true);
  };

  /**
   * @description: 关闭上传目录弹窗
   * @param {any} record
   * @return {void}
   */
  const closeUploadDBFDialog = (record: any): void => {
    setUploadDBFVisible(false);
    setActiveBatch({});
    if (record) {
      updateBatchList(record);
    }
  };

  const uploadFileFunc = (id: number) => {
    uploadBatch(id).then((res) => {
      console.log('入库', res.data);
    });
  };

  /**
   * @description: 根据传入的列表判断按钮是否展示
   * @param {number[]} allowList 允许展示的状态列表
   * @param {number} state 当前的状态
   * @return {boolean} 是否可以展示
   */
  const showBtnFunc = (allowList: number[], state: number): boolean => {
    return allowList.indexOf(state) >= 0;
  };

  const getItemListState = (list: any[]): boolean => {
    let _state = false;
    list.forEach((item) => {
      if (item.status) {
        _state = item.status;
      }
    });
    return _state;
  };

  const getOriginState = (item: any): boolean => {
    return item.attOriginal?.status;
  };

  const getCDState = (item: any): boolean => {
    return item.attOriginal?.status && item.attOriginalRule?.ruleType > 0;
  };

  const columns: ColumnsType = [
    { title: '序号', dataIndex: 'id', key: 'id', align: 'center' },
    { title: '名称', dataIndex: 'name', key: 'name', align: 'center' },
    {
      title: '接收方式',
      dataIndex: 'receiveMode',
      key: 'receiveMode',
      align: 'center',
      render: (type: number) => <Tag color="blue">{receiveModeFilter(type)}</Tag>
    },
    {
      title: '数据包类型',
      dataIndex: 'receiveType',
      key: 'receiveType',
      align: 'center',
      render: (type: number) => <span>{receiveTypeFilter(type)}</span>
    },
    { title: '来源单位', dataIndex: 'transferUnit', key: 'transferUnit', align: 'center' },
    {
      title: '所属全宗',
      dataIndex: ['fonds', 'fondName'],
      key: 'fonds',
      width: 120,
      align: 'center'
    },
    { title: '档案类型', dataIndex: ['archiveType', 'atName'], key: 'fonds', align: 'center' },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: 120,
      render: (text: any) => <span>{formatDate(text)}</span>
    },
    {
      title: '批次',
      dataIndex: 'batchNo',
      key: 'batchNo',
      align: 'center',
      width: 120,
      render: (text: any) => <span style={{ wordBreak: 'break-all' }}>{text}</span>
    },
    // { title: '原文大小', dataIndex: 'originalSize', key: 'originalSize', align: 'center' },
    // { title: '原文个数', dataIndex: 'originalSize', key: 'originalSize', align: 'center' },
    // { title: '条目数', dataIndex: 'originalSize', key: 'originalSize', align: 'center' },
    {
      title: '批次状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (status: number, record: any) => (
        <>
          {record.progress && record.progress < 100 && (
            <Progress percent={record.progress} steps={5} size="small" />
          )}
          <Tag color="blue">{stateFilter(status)}</Tag>
        </>
      )
    },
    selectReceiveType === RECEIVE_TYPE_EXCEL && {
      title: '档案包上传',
      key: 'attachmentExcel',
      align: 'center',
      render: (_val: any, record: any) => (
        <>
          <div>
            <Space>
              <div className={cx('attach--item')}>
                上传条目 |{' '}
                {getItemListState(record.attItemsList) ? (
                  <Typography.Text type="success">
                    <CheckCircleFilled />
                  </Typography.Text>
                ) : (
                  <Typography.Text type="warning">待上传</Typography.Text>
                )}
              </div>
              <Button
                size="small"
                type="link"
                onClick={() => {
                  showUploadFolderDialog(record);
                }}
              >
                管理
              </Button>
            </Space>
          </div>
          <div>
            <Space>
              <div className="attach--origin">
                上传原文 |{' '}
                {getOriginState(record) ? (
                  <Typography.Text type="success">
                    <CheckCircleFilled />
                  </Typography.Text>
                ) : (
                  <Typography.Text type="warning">待上传</Typography.Text>
                )}
              </div>
              <Button
                size="small"
                type="link"
                onClick={() => {
                  showUploadOriginDialog(record);
                }}
              >
                管理
              </Button>
            </Space>
          </div>
        </>
      )
    },
    selectReceiveType === RECEIVE_TYPE_SIP && {
      title: '附件上传',
      key: 'attachmentSip',
      align: 'center',
      render: (_val: any, record: any) => (
        <>
          <div>
            <Space>
              <div className={cx('attach--item')}>
                上传格式包 |{' '}
                {getOriginState(record) ? (
                  <Typography.Text type="success">
                    <CheckCircleFilled />
                  </Typography.Text>
                ) : (
                  <Typography.Text type="warning">待上传</Typography.Text>
                )}
              </div>
              <Button
                size="small"
                type="link"
                onClick={() => {
                  showUploadSipDialog(record);
                }}
              >
                管理
              </Button>
            </Space>
          </div>
        </>
      )
    },
    selectReceiveType === RECEIVE_TYPE_CD && {
      title: '附件上传',
      key: 'attachmentCD',
      align: 'center',
      render: (_val: any, record: any) => (
        <>
          <div>
            <Space>
              <div className={cx('attach--item')}>
                上传格式包 |{' '}
                {getCDState(record) ? (
                  <Typography.Text type="success">
                    <CheckCircleFilled />
                  </Typography.Text>
                ) : (
                  <Typography.Text type="warning">待上传</Typography.Text>
                )}
              </div>
              <Button
                size="small"
                type="link"
                onClick={() => {
                  showUploadCDDialog(record);
                }}
              >
                管理
              </Button>
            </Space>
          </div>
        </>
      )
    },
    selectReceiveType === RECEIVE_TYPE_DBF && {
      title: '附件上传',
      key: 'attachmentSip',
      align: 'center',
      render: (_val: any, record: any) => (
        <>
          <div>
            <Space>
              <div className={cx('attach--item')}>
                上传格式包 |{' '}
                {getOriginState(record) ? (
                  <Typography.Text type="success">
                    <CheckCircleFilled />
                  </Typography.Text>
                ) : (
                  <Typography.Text type="warning">待上传</Typography.Text>
                )}
              </div>
              <Button
                size="small"
                type="link"
                onClick={() => {
                  showUploadDBFDialog(record);
                }}
              >
                管理
              </Button>
            </Space>
          </div>
        </>
      )
    },
    { title: '附件', key: 'report', align: 'center' },
    { title: '审核反馈', key: 'audit', align: 'center' },
    {
      title: formatMessage('tableAction'),
      key: 'action',
      className: cx('action-col'),
      align: 'center',
      width: 140,
      render: (_text: any, record: any) => (
        <Space>
          {showBtnFunc([0], record.status) && (
            <Button type="link" size="small">
              接收
            </Button>
          )}
          {showBtnFunc([3, 8, 10], record.status) && (
            <Button
              type="link"
              size="small"
              onClick={() => {
                uploadFileFunc(record.id);
              }}
            >
              入库
            </Button>
          )}
          {showBtnFunc([8, 10], record.status) && (
            <Button type="link" size="small">
              下载
            </Button>
          )}
          {/* {showBtnFunc([ 5], record.status) && (
                <Button type="link" size="small">
                  检测
                </Button>
              )} */}
          {showBtnFunc([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], record.status) && (
            <Button
              type="link"
              size="small"
              danger
              onClick={() => {
                deleteBatchFunc(record.id);
              }}
            >
              删除
            </Button>
          )}
          {showBtnFunc([8, 9, 10], record.status) && (
            <Button type="link" size="small">
              打回
            </Button>
          )}
        </Space>
      )
    }
  ].filter((item) => item) as ColumnsType;

  return (
    <div className={className}>
      <Table
        columns={columns}
        dataSource={batchList}
        loading={loading}
        rowKey="id"
        rowSelection={rowSelection}
        bordered
        scroll={{ x: 'max-content' }}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      />

      {/* 接收、编辑弹窗 */}
      {useMemo(
        () =>
          selectData && (
            <CreateBatchDialog
              visible={createVisible}
              data={selectData}
              onClose={() => {
                setCreateVisible(false);
              }}
            />
          ),
        [createVisible]
      )}

      {/* 上传目录弹窗 */}
      {useMemo(
        () =>
          selectReceiveType === RECEIVE_TYPE_EXCEL && (
            <UploadFolderDialog
              visible={uploadFolderVisible}
              batchData={activeBatch}
              onClose={closeUploadFolderDialog}
            />
          ),
        [uploadFolderVisible, activeBatch]
      )}

      {/* 上传原文弹窗 */}
      {useMemo(
        () =>
          selectReceiveType === RECEIVE_TYPE_EXCEL && (
            <UploadOriginDialog visible={uploadOriginVisible} onClose={closeUploadOriginDialog} />
          ),
        [uploadOriginVisible, activeBatch]
      )}

      {/* 上传SIP包弹窗 */}
      {useMemo(
        () =>
          selectReceiveType === RECEIVE_TYPE_SIP && (
            <UploadSipDialog visible={uploadSipVisible} onClose={closeUploadSipDialog} />
          ),
        [uploadSipVisible, activeBatch]
      )}

      {/* 上传CD弹窗 */}
      {useMemo(
        () =>
          selectReceiveType === RECEIVE_TYPE_CD && (
            <UploadCDDialog visible={uploadCDVisible} onClose={closeUploadCDDialog} />
          ),
        [uploadCDVisible, activeBatch]
      )}

      {/* 上传DBF弹窗 */}
      {useMemo(
        () =>
          selectReceiveType === RECEIVE_TYPE_DBF && (
            <UploadDBFDialog visible={uploadDBFVisible} onClose={closeUploadDBFDialog} />
          ),
        [uploadDBFVisible, activeBatch]
      )}
    </div>
  );
};

export default observer(PageList);
